<template>
  <div class="insp">
    <div class="insp-header">
      <div class="flexBetween">
        <div class="flex insp-header-left">
          <el-select v-model="bridgeValue" placeholder="请选择区域" size="small" style="width: 180px;" class="mRight10"
                     clearable>
            <el-option v-for="item in bridgeOptsAll1" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
          <el-select v-model="historyStatus" placeholder="请选择桥型" size="small" style="width: 140px;" class="mRight10"
                     clearable>
            <el-option v-for="item in historyStatusOpts1" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <el-select v-model="historyStatus" placeholder="请选择生成状态" size="small" style="width: 140px;" class="mRight10"
                     clearable>
            <el-option v-for="item in historyStatusOpts1" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <el-button type="primary" size="small" @click="queryForPage(1)">
            查询
          </el-button>
        </div>
      </div>
    </div>

    <div class="insp-content">
      <div class="insp-table">
        <el-table :data="tableData" stripe :header-cell-style="{
          background: '#8595B9',
          color: '#fff',
          height: '44px',
        }" max-height="681px">
          <el-table-column type="index" width="50"></el-table-column>
          <el-table-column prop="area" label="区域" width="200" show-overflow-tooltip></el-table-column>
          <el-table-column prop="name" label="桥梁名称" width="200" show-overflow-tooltip></el-table-column>
          <el-table-column prop="qx" label="桥型" width="200" show-overflow-tooltip></el-table-column>
          <el-table-column prop="long" label="桥全长(m)" show-overflow-tooltip></el-table-column>
          <el-table-column prop="position" label="地理位置" show-overflow-tooltip></el-table-column>
          <el-table-column prop="time" label="生成时间" show-overflow-tooltip></el-table-column>

          <el-table-column label="结构详情" width="90">
            <template slot-scope="scope">
              <el-tooltip content="详情">
                <el-button type="text" icon="el-icon-document" @click="handelDetail(scope.row.id)">
                  生成
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="insp-page">
        <el-pagination background layout="prev, pager, next" :current-page.sync="currentPage"
                       :hide-on-single-page="false" @current-change="handlePageChange" :page-size="pageSize" :total="recordsTotal">
        </el-pagination>
      </div>
    </div>




  </div>
</template>
<script>
  import base from "@/api/base";
  import {
    config
  } from 'vuedraggable';
  export default {
    data() {
      var validateDease = (rule, value, callback) => {
        if (this.ruleForm.multipleSelection.length <= 0) {
          callback(new Error('请添加病害'));
        } else {
          callback();
        }
      };
      return {
        tableData: [{
          index: '1',
          area: '崇川区',
          name: '滨江大桥',
          qx: '桥式梁',
          long: '1200',
          position: '江苏省南通市崇川区',
          time: '2021-03-27',
        }, {
          index: '2',
          area: '崇川区',
          name: '城闸大桥',
          qx: '斜拉桥',
          long: '1200',
          position: '江苏省南通市崇川区',
          time: '2021-03-30',
        },{
          index: '3',
          area: '崇川区',
          name: '通吕一号桥',
          qx: '拱桥',
          long: '1200',
          position: '江苏省南通市崇川区',
          time: '2021-04-02',
        }],
        uploadParams: {},
        uploadUrl: base.UPLOADURL,
        pageSize: 6,
        currentPage: 1,
        recordsTotal: 0,
        historyName: '',
        historyStatus: '',
        historyStatusOpts: [{
          label: '待养护',
          value: 0
        }, {
          label: '养护中',
          value: 1
        }, {
          label: '已处理',
          value: 2
        }],
        bridgeValue: '',
        bridgeOptsAll: [],
        inspType: '',
        inspTypeOpts: [],
        dialogTitle: "",
        dialogVisible: false,
        tableDeaseData: [],
        editId: '',
       /* tableData: [],*/
        bridgeOptions: [],
        taskOptions: [],
        currentPage_sel: 1,
        recordsTotal_sel: 0,
        pagesize_sel: 10,
        currentPage_dease: 1,
        recordsTotal_dease: 0,
        pageSize_dease: 6,
        deasePosOptions: [],
        deaseLevelOptions: [{
          label: '一级',
          value: 0
        }, {
          label: '二级',
          value: 1
        }, {
          label: '三级',
          value: 2
        }],
        dialogImageUrl: '',
        dialogImgVisible: false,
        fileList: [],
        ruleForm: {
          task: "",
          inspBridge: "",
          deasePosition: [],
          deaseLevel: "",
          dease: "",
          deaseImage: [],
          problemNote: "",
          multipleSelection: [],
          diseaseUnits: []
        },
        rules: {
          task: [{
            required: true,
            message: "请选择任务",
            trigger: "change"
          }],
          inspBridge: [{
            required: true,
            message: "请选择巡检桥梁",
            trigger: "change"
          }],
          deasePosition: [{
            required: true,
            message: "请选择病害部位",
            trigger: "change"
          }],
          deaseLevel: [{
            required: true,
            message: "请选择病害程度",
            trigger: "change"
          }],
          dease: [{
            required: true,
            validator: validateDease,
            trigger: "click"
          }],
          deaseImage: [{
            required: true,
            message: "请选择病害图片",
            trigger: "change"
          }]
        },
        bridgeTypeId: '',
        deaseDialogVisible: false,
        diseaseValues: [],
        detailTitle: '巡检记录详情',
        detailVisible: false,
        detailInfo: {}
      };
    },
    watch: {
      '$route'(to, from) {
        this.queryTaskOpts(1);
      }
    },
    created() {
      this.queryBridgeList();
      this.queryTaskOpts(1);
      this.queryForPage(1);
    },
    methods: {
      emptyForm() {
        this.$refs["ruleForm"].resetFields();
        const emptyObj = {
          task: "",
          inspBridge: "",
          deasePosition: [],
          deaseLevel: "",
          dease: "",
          deaseImage: [],
          problemNote: "",
          multipleSelection: [],
          diseaseUnits: []
        }
        this.ruleForm = emptyObj;
      },
      handleAdd() {
        this.emptyForm();
        this.editId = null;
        this.dialogTitle = "新增巡检记录";
        this.dialogVisible = true;
      },
      handelEdit(val) {
        this.$refs["ruleForm"].resetFields();
        this.dialogTitle = "修改巡检记录";
        this.dialogVisible = true;
        this.editId = val;
        this.queryHistoryById(val);
      },
      handelDetail(val) {
        this.detailTitle = "巡检记录详情";
        this.detailVisible = true;
        this.$api.insp.queryHistoryById(val).then(response => {
          this.detailInfo = response.data.data || {};
        });
      },
      handleSubmit() {
        this.$refs.ruleForm.validate(async (valid) => {
          if (!valid) {
            return false;
          }
          let _userInfo = JSON.parse(localStorage.getItem("userInfo"));
          const _ext2 = this.ruleForm.deasePosition[2] ? this.ruleForm.deasePosition[2].split(';')[1] : '';
          if (!_ext2) {
            this.$vs.notify({
              text: '请病害部位选择至构件！',
              color: "danger"
            });
            return false;
          }
          let _ext3 = {
            level: this.ruleForm.deaseLevel,
            deasePosition: this.ruleForm.deasePosition,
            diseaseUnits: this.ruleForm.multipleSelection.length > 0 ?
              this.ruleForm.multipleSelection[0]['diseaseUnits'] : "",
          };
          this.ruleForm.diseaseUnits.forEach((item, index) => {
            _ext3[`unit${index}`] = item.value;
          });
          _ext3['diseaseValues'] = this.ruleForm.diseaseUnits;

          let _params = {
            userId: _userInfo['userid'] || '',
            userName: _userInfo['realname'] || '',
            taskId: this.ruleForm.task.split(';')[0] || '',
            name: this.ruleForm.inspBridge['name'] || '', //巡检项名称
            problemNote: this.ruleForm.problemNote,
            taskItemId: this.ruleForm.inspBridge['id'] || '',
            ownId: this.ruleForm.inspBridge['ownId'] || '',
            ownName: this.ruleForm.inspBridge['ownName'] || '',
            ext1: this.ruleForm.deaseImage.join(';'), //图片地址
            ext2: _ext2, //构件名称
            ext4: this.ruleForm.multipleSelection.length > 0 ? this.ruleForm.multipleSelection[0].id : '', //病害
            ext3: JSON.stringify(_ext3), //病害其他json
            ext6: this.ruleForm.multipleSelection.length > 0 ? this.ruleForm.multipleSelection[0].name :
              '' //病害名称
          };
          if (this.editId) {
            _params.id = this.editId;
          }

          if (this.editId) {
            this.$api.insp.updateHistory(_params).then(response => {
              if (response.data.success) {
                this.$vs.notify({
                  text: '修改成功',
                  color: "success"
                });
                this.dialogVisible = false;
                this.queryForPage(1);
                this.fileList = [];
              }
            });
          } else {
            this.$api.insp.addHistory(_params).then(response => {
              if (response.data.success) {
                this.$vs.notify({
                  text: '新增成功',
                  color: "success"
                });
                this.dialogVisible = false;
                this.queryForPage(1);
                this.fileList = [];
              }
            });
          }
        });
      },
      handelDelete(val) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$api.insp.deleteHistory(val).then(response => {
            if (response.data.success) {
              this.$vs.notify({
                text: '删除成功',
                color: "success",
                icon: "success"
              });
              let maxPage = Math.ceil((this.recordsTotal - 1) / this.pageSize);
              if (this.currentPage > maxPage) {
                this.currentPage = maxPage
              }
              this.handlePageChange(this.currentPage);
            } else {
              this.$vs.notify({
                text: "删除失败",
                color: "danger"
              })
            }
          })
        }).catch(() => {
          this.$vs.notify({
            text: "已取消删除",
            color: "primary"
          })
        });
      },
      queryForPage(pageIndex) {
        let _userInfo = JSON.parse(localStorage.getItem("userInfo"));
        if (pageIndex && pageIndex === 1) {
          this.currentPage = 1;
        }
        const _params = {
          pageSize: this.pageSize,
          pageNum: this.currentPage,
          data: {
            name: this.historyName,
            status: this.historyStatus,
            ownId: this.bridgeValue,
            userId: _userInfo['userid']||''
          }
        }
        /*this.$api.insp.queryHistoryPage(_params).then(response => {
          if (response.data.success) {
            this.tableData = response.data.data.map(item => {
              let _position = '';
              if (item.ext3) {
                _position =
                  `${JSON.parse(item.ext3)['deasePosition'][0].split(';')[1]}/${JSON.parse(item.ext3)['deasePosition'][1].split(';')[1]}`
              }
              let _unit = item.ext3 ? JSON.parse(item.ext3)['diseaseValues'] : [];
              let _images = item.ext1 ? item.ext1.split(';') : [];
              return {
                ...item,
                problemName: item.ext6 || '',
                billNo: item.billNo,
                position: _position,
                structure: item.ext2 || '',
                unit: _unit ? _unit.map(temp => `${temp.value}${temp.unit} `) : '',
                image: _images.length > 0 ? `${base.DOWNLOADURL}/${_images[0]}` : '',
                images: _images.map(temp => `${base.DOWNLOADURL}/${temp}`)
              }
            });
            this.recordsTotal = response.data.recordsTotal;
          }
        });*/
      },
      queryHistoryById(val) {
        this.$api.insp.queryHistoryById(val).then(response => {
          const _data = response.data.data || {};
          const _multipleSelection = [{
            id: _data.ext4,
            name: _data.ext3 ? JSON.parse(_data.ext3)['name'] ? JSON.parse(_data.ext3)['name'] : '' : '',
            diseaseUnits: _data.ext3 ? JSON.parse(_data.ext3)['diseaseUnits'] ? JSON.parse(_data.ext3)[
              'diseaseUnits'] : '' : ''
          }];
          let _ruleForm = {
            task: _data.taskId,
            inspBridge: {
              name: _data['name'] || '',
              ownId: _data['ownId'] || '',
              id: _data['taskItemId'] || '',
              ownName: _data['ownName'] || ''
            },
            problemNote: _data.problemNote,
            deaseLevel: _data.ext3 ? JSON.parse(_data.ext3)['level'] ? JSON.parse(_data.ext3)['level'] : 0 : '',
            multipleSelection: _multipleSelection,
            deasePosition: _data.ext3 ? JSON.parse(_data.ext3)['deasePosition'] ? JSON.parse(_data.ext3)[
              'deasePosition'] : [] : [],
            deaseImage: _data.ext1 ? _data.ext1.split(';') : [],
            diseaseUnits: _data.ext3 ? JSON.parse(_data.ext3)['diseaseValues'] ? JSON.parse(_data.ext3)[
              'diseaseValues'] : [] : [],
          };
          this.fileList = _ruleForm.deaseImage.map(item => ({
            filePath: item,
            url: `${base.DOWNLOADURL}/${item}`
          }));
          this.ruleForm = _ruleForm;
          this.diseaseValues = _data.ext3 ? JSON.parse(_data.ext3)['diseaseValues'] ? JSON.parse(_data.ext3)[
            'diseaseValues'] : [] : [];
          this.uploadParams = {
            ownId: _data.ownId
          }
          this.handleChangeTask(_ruleForm.task);
          this.handleBridgeChange(_ruleForm.inspBridge);
          this.queryDiseaseByStructureId(1);
        });
      },
      queryTaskOpts(pageIndex) {
        if (pageIndex && pageIndex === 1) {
          this.currentPage_sel = 1;
        }
        const _params = {
          pageSize: this.pagesize_sel,
          pageNum: this.currentPage_sel
        }
        this.$api.insp.queryTaskPage(_params).then(response => {
          if (response.data.success) {
            this.taskOptions = response.data.data;
            this.recordsTotal_sel = response.data.recordsTotal;
          }
        });
      },
      queryDiseaseByStructureId(pageIndex) {
        if (pageIndex && pageIndex === 1) {
          this.currentPage_dease = 1;
        }
        const _params = {
          pageNum: this.currentPage_dease,
          pageSize: this.pageSize_dease,
          structureId: this.ruleForm.deasePosition[1].split(';')[0]
        };
        this.$api.bridge.queryDiseaseByStructureId(_params).then(response => {
          if (response.data.success) {
            this.tableDeaseData = response.data.data[0];

            if (!this.editId) {
              this.ruleForm.multipleSelection = [];
            } else {
              if (this.ruleForm.multipleSelection && this.ruleForm.multipleSelection.length > 0) {
                this.ruleForm.multipleSelection.forEach(item => {
                  this.tableDeaseData.forEach(row => {
                    if (row.id === item.id) {
                      this.$nextTick(() => {
                        this.$refs.multipleTable.toggleRowSelection(row, true);
                        this.ruleForm.diseaseUnits = this.diseaseValues;
                      });
                    }
                  })
                })
              }
            }
          }
        });
      },
      deepDeasePosOptions(data) {
        let _arr = [];
        let _obj = {};
        data.forEach(item => {
          const _tmp = {
            ...item
          };
          if (_tmp.children && _tmp.children.length > 0) {
            _tmp.children = this.deepDeasePosOptions(_tmp.children);
          }
          _obj = {
            id: _tmp.id,
            name: _tmp.name,
            value: `${_tmp.id};${_tmp.name}`,
          }
          if (_tmp.children && _tmp.children.length > 0) {
            _obj.children = _tmp.children;
          }
          _arr.push(_obj);
        });
        return _arr;
      },
      queryConstructionModelTreeById(_params) {
        this.$api.bridge.queryStructuralElementTree(_params).then(response => {
          if (response.data.success) {
            this.deasePosOptions = this.deepDeasePosOptions(response.data.data.children);
          }
        });
      },
      handlePageChange(currentPage) {
        this.currentPage = currentPage;
        this.queryForPage();
      },
      handlePageChange_sel(currentPage) {
        this.currentPage_sel = currentPage;
        this.queryTaskOpts();
      },
      handlePageChange_dease(currentPage) {
        this.currentPage_sel = currentPage;
        this.queryDiseaseByStructureId();
      },
      handleChangeTask(val) {
        this.$api.insp.queryTaskById(val.split(';')[0]).then(response => {
          const _data = response.data.data;
          this.bridgeOptions = _data.itemList;
        });
      },
      handleBridgeChange(event) {
        this.uploadParams = {
          ownId: event['ownId'] || ''
        }
        this.$api.bridge.queryBridgeBasicById({
          bridgeId: event['ownId'] ||''
        }).then(response => {
          const _bridgeTypeId = response.data.data[0][0].bridgeTypeId;
          const _params = {
            bridgeTypeId: _bridgeTypeId,
            pId: '-1',
            bridgeId: event['ownId'] || ''
          };
          this.queryConstructionModelTreeById(_params);
        });
      },
      handleChangeDeasePos(val) {
        this.ruleForm.deasePosition = val;
      },
      handlePictureCardRemove(file, fileList) {
        this.handleFileChange(fileList);
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogImgVisible = true;
      },
      handlePictureCardSuccess(res, file, fileList) {
        this.handleFileChange(fileList);
      },
      handleFileChange(fileList) {
        let _pathList = [];
        if (fileList && fileList.length > 0) {
          fileList.forEach(item => {
            if (item.response) {
              if (item.response.code === 200) {
                let _files = item.response.data.successFiles;
                if (_files) {
                  const _filePath = _files[0].filePath;
                  const _name = _files[0].originalFileName;
                  _pathList.push(_filePath);
                }
              }
            } else if (item.status === 'success') {
              _pathList.push(item.filePath);
            }
          })
        }
        this.$set(this.ruleForm, 'deaseImage', _pathList);
      },
      cancelSubmit() {
        this.dialogVisible = false;
        this.fileList = [];
      },
      handleAddDease() {
        if (this.ruleForm.deasePosition.length <= 0) {
          this.$vs.notify({
            text: "请先选择病害部位！",
            color: "danger"
          })
          return false;
        }
        this.queryDiseaseByStructureId(1);
        this.deaseDialogVisible = true;
      },
      handleSelectionChange(val) {
        this.ruleForm.multipleSelection = val.map(item => {
          const _deaseUnits = item['diseaseUnits'] ? item['diseaseUnits'].split(';') : [];
          this.ruleForm.diseaseUnits = _deaseUnits.map((item) => {
            return {
              unit: item,
              value: 0
            }
          });
          return {
            id: item.id,
            name: item.name,
            diseaseUnits: item.diseaseUnits
          }
        });
      },
      handleDeaseSubmit() {
        if (this.ruleForm.multipleSelection && this.ruleForm.multipleSelection.length > 1) {
          this.$vs.notify({
            text: "病害只能选择一条",
            color: "danger"
          })
          return false;
        }
        this.deaseDialogVisible = false;
      },
      cancelDease() {
        this.deaseDialogVisible = false;
      },
      cancelDetail() {
        this.detailVisible = false;
      },
      queryBridgeList() {
        this.$api.bridge.AllTheBridges().then(response => {
          if (response.data.success) {
            this.bridgeOptsAll = response.data.data[0];
          }
        });
      },
      historyStatusClass(type) {
        switch (type) {
          case 0:
            return 'inspTypeA';
          case 1:
            return 'inspTypeB';
          case 2:
            return 'inspTypeC';
        }
      },
      historyStatusText(type) {
        switch (type) {
          case 0:
            return '待养护';
          case 1:
            return '养护中';
          case 2:
            return '已处理';
        }
      }
    },
    computed: {
      computedUnit() {
        let _diseaseUnits = this.detailInfo['ext3'] ? JSON.parse(this.detailInfo['ext3'])['diseaseValues'] : [];
        let _string = _diseaseUnits ? _diseaseUnits.map(item => `${item.value} ${item.unit}`).join(' ') : '';
        return _string;
      },
      computedPosition() {
        let _deasePosition = this.detailInfo['ext3'] ? JSON.parse(this.detailInfo['ext3'])['deasePosition'] : [];
        let _string = _deasePosition ? _deasePosition.map(item => `${item.split(';')[1]}`).join('/') : '';
        return _string;
      },
      computedImageList() {
        let _list = this.detailInfo['ext1'] ? this.detailInfo['ext1'].split(';') : [];
        return _list.map(item => `${base.DOWNLOADURL}/${item}`);
      }
    }
  };

</script>
<style scoped lang="scss">
  @import './insp.scss';

  /deep/.el-table__header tr,
  /deep/.el-table__header th {
    padding: 0;
    height: 44px;
  }

  /deep/.el-table td,
  /deep/.el-table th {
    text-align: center;
    font-size: 14px;
  }

  /deep/.el-table th {
    font-weight: 500;
    color: #fff;
  }

  /deep/.el-table td {
    font-weight: 400;
    color: #444;
    padding: 0;
    height: 44px;
    line-height: 44px;
  }

  /deep/.el-table--striped .el-table__body tr.el-table__row--striped td {
    background: #F1F5FC;
  }

  /deep/.el-upload--picture-card {
    width: 70px;
    height: 70px;
    line-height: 74px;
  }

  /deep/.el-upload-list--picture-card .el-upload-list__item {
    width: 72px;
    height: 72px;
  }

  /deep/.el-dialog.image {
    background: #fff;
    width: 900px;
    max-height: 700px;
    overflow-y: scroll;
    margin-top: 10vh !important
  }

  /deep/.el-dialog__body {
    width: 100%;
    height: 100%;
  }

</style>
